# 书签功能API

from fastapi import APIRouter, Request, HTTPException, Body
from pydantic import BaseModel
from typing import List, Optional
import json
import os
import re
from datetime import datetime

# 创建路由
router = APIRouter()

# 书签数据模型
class Bookmark(BaseModel):
    id: Optional[str] = None
    title: str
    url: str
    category: str
    description: Optional[str] = None
    create_time: Optional[str] = None

# 书签数据文件路径
BOOKMARKS_FILE = "data/bookmarks.json"

# 确保数据目录存在
os.makedirs(os.path.dirname(BOOKMARKS_FILE), exist_ok=True)

# 读取书签数据
def read_bookmarks():
    if not os.path.exists(BOOKMARKS_FILE):
        return {"categories": ["工具", "常用网站"], "bookmarks": []}
    
    try:
        with open(BOOKMARKS_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception as e:
        print(f"读取书签数据出错: {e}")
        return {"categories": ["工具", "常用网站"], "bookmarks": []}

# 保存书签数据
def save_bookmarks(data):
    try:
        with open(BOOKMARKS_FILE, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存书签数据出错: {e}")
        return False

# 获取所有书签
@router.get("/all")
async def get_all_bookmarks():
    return read_bookmarks()

# 添加新书签
@router.post("/add")
async def add_bookmark(bookmark: Bookmark):
    data = read_bookmarks()
    
    # 生成唯一ID
    bookmark_id = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{len(data['bookmarks'])}"
    
    # 添加创建时间
    new_bookmark = bookmark.dict()
    new_bookmark["id"] = bookmark_id
    new_bookmark["create_time"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # 如果是新类别，添加到类别列表
    if bookmark.category not in data["categories"]:
        data["categories"].append(bookmark.category)
    
    # 添加书签
    data["bookmarks"].append(new_bookmark)
    
    if save_bookmarks(data):
        return {"success": True, "bookmark": new_bookmark}
    else:
        raise HTTPException(status_code=500, detail="保存书签失败")

# 更新书签
@router.put("/update/{bookmark_id}")
async def update_bookmark(bookmark_id: str, bookmark: Bookmark):
    data = read_bookmarks()
    
    # 查找并更新书签
    for i, bm in enumerate(data["bookmarks"]):
        if bm["id"] == bookmark_id:
            # 保留原始ID和创建时间
            updated_bookmark = bookmark.dict()
            updated_bookmark["id"] = bookmark_id
            updated_bookmark["create_time"] = bm["create_time"]
            
            # 如果是新类别，添加到类别列表
            if bookmark.category not in data["categories"]:
                data["categories"].append(bookmark.category)
            
            # 更新书签
            data["bookmarks"][i] = updated_bookmark
            
            if save_bookmarks(data):
                return {"success": True, "bookmark": updated_bookmark}
            else:
                raise HTTPException(status_code=500, detail="更新书签失败")
    
    raise HTTPException(status_code=404, detail="书签不存在")

# 删除书签
@router.delete("/delete/{bookmark_id}")
async def delete_bookmark(bookmark_id: str):
    data = read_bookmarks()
    
    # 查找并删除书签
    for i, bm in enumerate(data["bookmarks"]):
        if bm["id"] == bookmark_id:
            deleted = data["bookmarks"].pop(i)
            
            if save_bookmarks(data):
                return {"success": True, "deleted": deleted}
            else:
                raise HTTPException(status_code=500, detail="删除书签失败")
    
    raise HTTPException(status_code=404, detail="书签不存在")

# 搜索书签
@router.post("/search")
async def search_bookmarks(search_data: dict = Body(...)):
    data = read_bookmarks()
    search_text = search_data.get("text", "")
    search_type = search_data.get("type", "all")
    
    if not search_text:
        return {"bookmarks": []}
    
    try:
        pattern = re.compile(search_text, re.IGNORECASE)
    except re.error:
        # 如果正则表达式无效，则使用普通文本匹配
        pattern = search_text.lower()
    
    results = []
    
    for bm in data["bookmarks"]:
        match = False
        
        if search_type == "title" or search_type == "all":
            if isinstance(pattern, re.Pattern):
                if pattern.search(bm["title"]):
                    match = True
            elif pattern in bm["title"].lower():
                match = True
        
        if (search_type == "category" or search_type == "all") and not match:
            if isinstance(pattern, re.Pattern):
                if pattern.search(bm["category"]):
                    match = True
            elif pattern in bm["category"].lower():
                match = True
        
        if (search_type == "description" or search_type == "all") and not match:
            if bm.get("description"):
                if isinstance(pattern, re.Pattern):
                    if pattern.search(bm["description"]):
                        match = True
                elif pattern in bm["description"].lower():
                    match = True
        
        if match:
            results.append(bm)
    
    return {"bookmarks": results}

# 获取所有类别
@router.get("/categories")
async def get_categories():
    data = read_bookmarks()
    return {"categories": data["categories"]}

# 添加新类别
@router.post("/categories/add")
async def add_category(category_data: dict = Body(...)):
    data = read_bookmarks()
    new_category = category_data.get("category", "")
    
    if not new_category:
        raise HTTPException(status_code=400, detail="类别名称不能为空")
    
    if new_category in data["categories"]:
        raise HTTPException(status_code=400, detail="类别已存在")
    
    data["categories"].append(new_category)
    
    if save_bookmarks(data):
        return {"success": True, "categories": data["categories"]}
    else:
        raise HTTPException(status_code=500, detail="添加类别失败")